package com.example.shiXun.service.impl;

import com.example.shiXun.base.result.Results;
import com.example.shiXun.dao.RoleUserDao;
import com.example.shiXun.domain.SysRoleUser;
import com.example.shiXun.domain.SysUser;
import com.example.shiXun.dao.UserDao;
import com.example.shiXun.dto.UserDto;
import com.example.shiXun.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author ：meet
 * @date ：Created in 2020/4/11 21:53
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleUserDao roleUserDao;

    @Override
    public SysUser getUser(String username) {
        return null;
    }

    @Override
    public Results save(SysUser user, Integer roleId) {
        if (roleId != null) {
            userDao.save(user);

            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setUserId(user.getId().intValue());
            sysRoleUser.setRoleId(roleId);
            roleUserDao.save(sysRoleUser);
            return Results.success();
        }

        return Results.failure();
    }

    @Override
    public Results<SysUser> getAllUsersByPage(Integer offset, Integer limit) {
        return Results.success(userDao.countAllUsers().intValue(), userDao.getAllUsersByPage(offset, limit));
    }

    @Override
    public SysUser getUserByPhone(String telephone) {
        return userDao.getUserByPhone(telephone);
    }

    @Override
    public SysUser getUserByEmail(String email) {
        return userDao.getUserByEmail(email);
    }

    @Override
    public SysUser getUserById(Long id) {
        return userDao.getUserById(id);
    }

    @Override
    public Results<SysUser> updateUser(UserDto userDto, Integer roleId) {
        if (roleId != null) {
            userDao.updateUser(userDto);

            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setRoleId(roleId);
            sysRoleUser.setUserId(userDto.getId().intValue());

            if (roleUserDao.getSysRoleUserByUserId(userDto.getId().intValue())!=null){
                roleUserDao.updateSysRoleUser(sysRoleUser);
            }else {
                roleUserDao.save(sysRoleUser);
            }

            return Results.success();
        }else {
            return Results.failure();
        }


    }

    @Override
    public int deleteUser(Long id) {

        roleUserDao.deleteRoleUserByUserId(id.intValue());
        return userDao.deleteUserById(id.intValue());
    }

    @Override
    public Results<SysUser> getUserByFuzzyUsername(String username, Integer offset, Integer limit) {
        return Results.success(userDao.getUserByFuzzyUsername(username).intValue(),userDao.getUserByFuzzyUsernameAndPage(username,offset,limit));
    }


}
